<script setup lang="ts">
import { ref, reactive, onMounted, h } from 'vue';
import { NButton, NCard, NSpace, NDataTable, NPopconfirm, NTag, useMessage } from 'naive-ui';
import type { DataTableColumns } from 'naive-ui';
import { fetchDevTaskList, deleteDevTask, publishDevTask, offlineDevTask, type DevTask } from '@/service/api/dataplatform/dev';
import DevTaskOperateDrawer from './modules/dev-task-operate-drawer.vue';
import DevInstanceDrawer from './modules/dev-instance-drawer.vue';
import SqlEditorModal from './modules/sql-editor-modal.vue';

const message = useMessage();

const loading = ref(false);
const taskList = ref<DevTask[]>([]);
const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50, 100]
});

// 查询参数
const queryParams = reactive({
  name: '',
  taskType: '',
  status: undefined as number | undefined
});

// 抽屉和弹窗状态
const operateDrawerVisible = ref(false);
const instanceDrawerVisible = ref(false);
const sqlEditorVisible = ref(false);
const currentTask = ref<DevTask | null>(null);
const operateType = ref<'add' | 'edit'>('add');

// 表格列定义
const columns: DataTableColumns<DevTask> = [
  { title: '任务名称', key: 'name', width: 200, ellipsis: { tooltip: true } },
  {
    title: '任务类型',
    key: 'taskType',
    width: 120,
    render: (row) => {
      const typeMap: Record<string, { label: string; type: any }> = {
        SQL: { label: 'SQL', type: 'info' },
        PYTHON: { label: 'Python', type: 'success' },
        SHELL: { label: 'Shell', type: 'warning' },
        FLINK: { label: 'Flink', type: 'error' }
      };
      const config = typeMap[row.taskType] || { label: row.taskType, type: 'default' };
      return h(NTag, { type: config.type }, { default: () => config.label });
    }
  },
  { title: '数据源', key: 'datasourceName', width: 150, ellipsis: { tooltip: true } },
  { title: '执行引擎', key: 'engineType', width: 120 },
  {
    title: '状态',
    key: 'status',
    width: 100,
    render: (row) => {
      const statusMap: Record<number, { label: string; type: any }> = {
        0: { label: '草稿', type: 'default' },
        1: { label: '已发布', type: 'success' },
        2: { label: '已下线', type: 'warning' }
      };
      const config = statusMap[row.status || 0];
      return h(NTag, { type: config.type }, { default: () => config.label });
    }
  },
  { title: '描述', key: 'description', ellipsis: { tooltip: true } },
  { title: '创建时间', key: 'createTime', width: 180 },
  {
    title: '操作',
    key: 'actions',
    width: 300,
    fixed: 'right',
    render: (row) => {
      const buttons = [
        h(NButton, { size: 'small', onClick: () => handleEdit(row) }, { default: () => '编辑' }),
        h(NButton, { size: 'small', type: 'primary', onClick: () => handleOpenEditor(row) }, { default: () => '执行' }),
        h(NButton, { size: 'small', onClick: () => handleViewInstances(row) }, { default: () => '实例' })
      ];

      if (row.status === 0) {
        buttons.push(
          h(NButton, { size: 'small', type: 'success', onClick: () => handlePublish(row.id!) }, { default: () => '发布' })
        );
      }

      if (row.status === 1) {
        buttons.push(
          h(NButton, { size: 'small', type: 'warning', onClick: () => handleOffline(row.id!) }, { default: () => '下线' })
        );
      }

      buttons.push(
        h(
          NPopconfirm,
          { onPositiveClick: () => handleDelete(row.id!) },
          {
            default: () => '确认删除该任务吗？',
            trigger: () => h(NButton, { size: 'small', type: 'error' }, { default: () => '删除' })
          }
        )
      );

      return h(NSpace, null, { default: () => buttons });
    }
  }
];

// 加载数据
async function loadData() {
  loading.value = true;
  try {
    const params = {
      ...queryParams,
      pageNum: pagination.page,
      pageSize: pagination.pageSize
    };
    const res = await fetchDevTaskList(params);
    if (res.data) {
      taskList.value = res.data.rows || [];
      pagination.itemCount = res.data.total || 0;
    }
  } catch (error) {
    message.error('加载数据失败');
  } finally {
    loading.value = false;
  }
}

// 查询
function handleQuery() {
  pagination.page = 1;
  loadData();
}

// 重置
function handleReset() {
  Object.assign(queryParams, {
    name: '',
    taskType: '',
    status: undefined
  });
  handleQuery();
}

// 新增
function handleAdd() {
  operateType.value = 'add';
  currentTask.value = null;
  operateDrawerVisible.value = true;
}

// 编辑
function handleEdit(row: DevTask) {
  operateType.value = 'edit';
  currentTask.value = row;
  operateDrawerVisible.value = true;
}

// 删除
async function handleDelete(id: number) {
  try {
    await deleteDevTask(id);
    message.success('删除成功');
    loadData();
  } catch (error) {
    message.error('删除失败');
  }
}

// 发布
async function handlePublish(id: number) {
  try {
    await publishDevTask(id);
    message.success('发布成功');
    loadData();
  } catch (error) {
    message.error('发布失败');
  }
}

// 下线
async function handleOffline(id: number) {
  try {
    await offlineDevTask(id);
    message.success('下线成功');
    loadData();
  } catch (error) {
    message.error('下线失败');
  }
}

// 打开编辑器
function handleOpenEditor(row: DevTask) {
  currentTask.value = row;
  sqlEditorVisible.value = true;
}

// 查看实例
function handleViewInstances(row: DevTask) {
  currentTask.value = row;
  instanceDrawerVisible.value = true;
}

// 操作成功回调
function handleOperateSuccess() {
  operateDrawerVisible.value = false;
  loadData();
}

// 分页变化
function handlePageChange(page: number) {
  pagination.page = page;
  loadData();
}

function handlePageSizeChange(pageSize: number) {
  pagination.pageSize = pageSize;
  pagination.page = 1;
  loadData();
}

onMounted(() => {
  loadData();
});
</script>

<template>
  <div class="h-full flex-col-stretch gap-16px overflow-hidden lt-sm:overflow-auto">
    <NCard title="数据开发" :bordered="false" size="small" class="sm:flex-1-hidden card-wrapper">
      <template #header-extra>
        <NButton type="primary" size="small" @click="handleAdd">
          <icon-ic-round-plus class="mr-4px text-20px" />
          新增任务
        </NButton>
      </template>

      <!-- 查询表单 -->
      <div class="mb-16px">
        <NSpace>
          <n-input v-model:value="queryParams.name" placeholder="任务名称" clearable style="width: 200px"
            @keyup.enter="handleQuery" />
          <n-select v-model:value="queryParams.taskType" placeholder="任务类型" clearable style="width: 150px" :options="[
            { label: 'SQL', value: 'SQL' },
            { label: 'Python', value: 'PYTHON' },
            { label: 'Shell', value: 'SHELL' },
            { label: 'Flink', value: 'FLINK' }
          ]" />
          <n-select v-model:value="queryParams.status" placeholder="状态" clearable style="width: 120px" :options="[
            { label: '草稿', value: 0 },
            { label: '已发布', value: 1 },
            { label: '已下线', value: 2 }
          ]" />
          <NButton type="primary" @click="handleQuery">
            <icon-ic-round-search class="mr-4px text-20px" />
            查询
          </NButton>
          <NButton @click="handleReset">
            <icon-ic-round-refresh class="mr-4px text-20px" />
            重置
          </NButton>
        </NSpace>
      </div>

      <!-- 数据表格 -->
      <NDataTable :columns="columns" :data="taskList" :loading="loading" :pagination="pagination" :scroll-x="1400"
        flex-height class="sm:h-full" @update:page="handlePageChange" @update:page-size="handlePageSizeChange" />
    </NCard>

    <!-- 任务操作抽屉 -->
    <DevTaskOperateDrawer v-model:visible="operateDrawerVisible" :operate-type="operateType" :row-data="currentTask"
      @success="handleOperateSuccess" />

    <!-- 实例列表抽屉 -->
    <DevInstanceDrawer v-model:visible="instanceDrawerVisible" :task="currentTask" />

    <!-- SQL编辑器弹窗 -->
    <SqlEditorModal v-model:visible="sqlEditorVisible" :task="currentTask" />
  </div>
</template>

<style scoped></style>
